/*
 * Copyright (c) 2009-2010 HIT Microelectronic Center
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *
 * Authors: Gou Pengfei
 *          Jin Yinghan
 *
 * Date: Dec. 2009
 *
 */

#ifndef __CPU_EDGE_COMMIT_HH__
#define __CPU_EDGE_COMMIT_HH__

#include <algorithm>
#include <numeric>

#include "base/statistics.hh"
#include "base/timebuf.hh"
#include "cpu/exetrace.hh"
#include "cpu/inst_seq.hh"
#include "cpu/edge/edge_sim_point.hh"

class DerivEdgeCPUParams;

template <class>
class EdgeThreadState;

template<class Impl>
class SimpleEdgeCommit
{
  public:
    // Typedefs from the Impl.
    typedef typename Impl::CPU CPU;
    typedef typename Impl::DynInstPtr DynInstPtr;
    typedef typename Impl::EdgeBlockPtr EdgeBlockPtr;
    typedef typename Impl::CPUPol CPUPol;

    //typedef typename CPUPol::RenameMap RenameMap;
    typedef typename CPUPol::ROB ROB;

    typedef typename CPUPol::TimeStruct TimeStruct;
    typedef typename CPUPol::Fetch2Map Fetch2Map;
    typedef typename CPUPol::Execute2Commit Execute2Commit;
    typedef typename CPUPol::Map2Execute Map2Execute;

    typedef typename CPUPol::Fetch Fetch;
    typedef typename CPUPol::Execute Execute;

    typedef EdgeThreadState<Impl> Thread;

    /** Event class used to schedule a squash due to a trap (fault or
     * interrupt) to happen on a specific cycle.
     */
    class TrapEvent : public Event {
      private:
        SimpleEdgeCommit<Impl> *commit;
        ThreadID tid;

      public:
        TrapEvent(SimpleEdgeCommit<Impl> *_commit, ThreadID _tid);

        void process();
        const char *description() const;
    };

    /** Overall commit status. Used to determine if the CPU can deschedule
     * itself due to a lack of activity.
     */
    enum CommitStatus{
        Active,
        Inactive
    };

    /** Individual thread status. */
    enum ThreadStatus {
        Running,
        Idle,
        ROBSquashing,
        TrapPending,
        FetchTrapPending
    };

    /** Commit policy for SMT mode. */
    enum CommitPolicy {
        Aggressive,
        RoundRobin,
        OldestReady
    };

  private:
    /** Overall commit status. */
    CommitStatus _status;
    /** Next commit status, to be set at the end of the cycle. */
    CommitStatus _nextStatus;
    /** Per-thread status. */
    ThreadStatus commitStatus[Impl::MaxThreads];
    /** Commit policy used in SMT mode. */
    CommitPolicy commitPolicy;

  public:
    /** Construct a SimpleEdgeCommit with the given parameters. */
    SimpleEdgeCommit(CPU *_cpu, DerivEdgeCPUParams *params);

    ~SimpleEdgeCommit();

    /** Returns the name of the SimpleEdgeCommit. */
    std::string name() const;

    /** Registers statistics. */
    void regStats();

    /** Sets the list of threads. */
    void setThreads(std::vector<Thread *> &threads);

    /** Sets the main time buffer pointer, used for backwards communication. */
    void setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr);

    void setFetchQueue(TimeBuffer<Fetch2Map> *fq_ptr);

    /** Sets the pointer to the queue coming from rename. */
    void setMapQueue(TimeBuffer<Map2Execute> *rq_ptr);

    /** Sets the pointer to the queue coming from IEW. */
    void setExecuteQueue(TimeBuffer<Execute2Commit> *iq_ptr);

    /** Sets the pointer to the IEW stage. */
    void setExecuteStage(Execute *execute_stage);

    /** Skid buffer between map and commit. */
    //std::queue<DynInstPtr> skidBuffer;
    std::queue<EdgeBlockPtr> skidBuffer;

    /** The pointer to the Execute stage. Used solely to ensure that
     * various events (traps, interrupts, syscalls) do not occur until
     * all stores have written back.
     */
    Execute *executeStage;

    /** Sets pointer to list of active threads. */
    void setActiveThreads(std::list<ThreadID> *at_ptr);

    /** Sets pointer to the commited state rename map. */
    //void setRenameMap(RenameMap rm_ptr[Impl::MaxThreads]);

    /** Sets pointer to the ROB. */
    void setROB(ROB *rob_ptr);

    /** Initializes stage by sending back the number of free entries. */
    void initStage();

    /** Initializes the draining of commit. */
    bool drain();

    /** Resumes execution after draining. */
    void resume();

    /** Completes the switch out of commit. */
    void switchOut();

    /** Takes over from another CPU's thread. */
    void takeOverFrom();

    /** Ticks the commit stage, which tries to commit instructions. */
    void tick();

    /** Handles any squashes that are sent from IEW, and adds instructions
     * to the ROB and tries to commit instructions.
     */
    void commit();

    /** Returns the number of free ROB entries for a specific thread. */
    size_t numROBFreeEntries(ThreadID tid);

    /** Generates an event to schedule a squash due to a trap. */
    void generateTrapEvent(ThreadID tid);

    /** Records that commit needs to initiate a squash due to an
     * external state update through the TC.
     */
    void generateTCEvent(ThreadID tid);

  private:
    /** Updates the overall status of commit with the nextStatus, and
     * tell the CPU if commit is active/inactive.
     */
    void updateStatus();

    /** Sets the next status based on threads' statuses, which becomes the
     * current status at the end of the cycle.
     */
    void setNextStatus();

    /** Checks if the ROB is completed with squashing. This is for the case
     * where the ROB can take multiple cycles to complete squashing.
     */
    bool robDoneSquashing();

    /** Returns if any of the threads have the number of ROB entries changed
     * on this cycle. Used to determine if the number of free ROB entries needs
     * to be sent back to previous stages.
     */
    bool changedROBEntries();

    /** Squashes all in flight instructions. */
    void squashAll(ThreadID tid);

    /** Handles squashing due to a trap. */
    void squashFromTrap(ThreadID tid);

    /** Handles squashing due to an TC write. */
    void squashFromTC(ThreadID tid);

    /** Commits as many instructions as possible. */
    void commitInstBlocks();

    /** Tries to commit the head ROB instruction passed in.
     * @param head_inst The instruction to be committed.
     */
    bool commitHead(EdgeBlockPtr &head_inst_block, unsigned inst_block_num);

    /** Gets instructions from rename and inserts them into the ROB. */
    void getInstBlocks();

    /** Insert all instructions from rename into skidBuffer */
    void skidInsert();

    /** Marks completed instructions using information sent from IEW. */
    void markCompletedInstBlocks();

    /** Gets the thread to commit, based on the SMT policy. */
    ThreadID getCommittingThread();

    /** Returns the thread ID to use based on a round robin policy. */
    ThreadID roundRobin();

    /** Returns the thread ID to use based on an oldest instruction policy. */
    ThreadID oldestReady();

    /** Updates commit stats based on this instruction. */
    void updateComInstBlockStats(EdgeBlockPtr &inst_block);

  public:
    /** Returns the PC of the head instruction of the ROB.
     * @todo: Probably remove this function as it returns only thread 0.
     */
    Addr readPC() { return PC[0]; }

    /** Returns the PC of a specific thread. */
    Addr readPC(ThreadID tid) { return PC[tid]; }

    /** Sets the PC of a specific thread. */
    void setPC(Addr val, ThreadID tid) { PC[tid] = val; }

    /** Reads the next PC of a specific thread. */
    Addr readNextPC(ThreadID tid) { return nextPC[tid]; }

    /** Sets the next PC of a specific thread. */
    void setNextPC(Addr val, ThreadID tid) { nextPC[tid] = val; }

    /** Reads the next NPC of a specific thread. */
    Addr readNextNPC(ThreadID tid) { return nextNPC[tid]; }

    /** Sets the next NPC of a specific thread. */
    void setNextNPC(Addr val, ThreadID tid) { nextNPC[tid] = val; }

    /** Dump the instruction block stats when call back happens. */
    void dumpInstBlockStat();

  private:
    /** Time buffer interface. */
    TimeBuffer<TimeStruct> *timeBuffer;

    /** Wire to write information heading to previous stages. */
    typename TimeBuffer<TimeStruct>::wire toExecute;

    /** Wire to read information from Execute (for ROB). */
    typename TimeBuffer<TimeStruct>::wire robInfoFromExecute;

    TimeBuffer<Fetch2Map> *fetch2commitQueue;

    typename TimeBuffer<Fetch2Map>::wire fromFetch;

    /** Execute instruction block queue interface. */
    TimeBuffer<Execute2Commit> *execute2commitQueue;

    /** Wire to read information from IEW queue. */
    typename TimeBuffer<Execute2Commit>::wire fromExecute;

    /** map instruction queue interface, for ROB. */
    TimeBuffer<Map2Execute> *map2commitQueue;

    /** Wire to read information from map queue. */
    typename TimeBuffer<Map2Execute>::wire fromMap;

  public:
    /** ROB interface. */
    ROB *rob;

    /** Simpoint for EDGE simulation. */
    EdgeSimPoint<Impl> *simPoint;

    /** Indicate if simpoint simulation is enable. */ 
    bool simPointSim;

  private:
    /** Pointer to CPU. */
    CPU *cpu;

    /** Vector of all of the threads. */
    std::vector<Thread *> thread;

    /** Records that commit has written to the time buffer this cycle. Used for
     * the CPU to determine if it can deschedule itself if there is no activity.
     */
    bool wroteToTimeBuffer;

    /** Records if the number of ROB entries has changed this cycle. If it has,
     * then the number of free entries must be re-broadcast.
     */
    bool changedROBNumEntries[Impl::MaxThreads];

    /** A counter of how many threads are currently squashing. */
    ThreadID squashCounter;

    /** Records if a thread has to squash this cycle due to a trap. */
    bool trapSquash[Impl::MaxThreads];

    /** Records if a thread has to squash this cycle due to an XC write. */
    bool tcSquash[Impl::MaxThreads];

    /** Priority List used for Commit Policy */
    std::list<ThreadID> priority_list;

    /** Execute to Commit delay, in ticks. */
    unsigned executeToCommitDelay;

    /** Commit to IEW delay, in ticks. */
    unsigned commitToExecuteDelay;

    /** Map to ROB delay, in ticks. */
    unsigned mapToROBDelay;

    unsigned fetchToCommitDelay;

    /** Rename width, in instructions.  Used so ROB knows how many
     *  instructions to get from the rename instruction queue.
     */
    unsigned mapWidth;

    /** Commit width, in instructions. */
    unsigned commitWidth;

    /** Number of Reorder Buffers */
    unsigned numRobs;

    /** Number of Active Threads */
    ThreadID numThreads;

    /** Is a drain pending. */
    bool drainPending;

    /** Is commit switched out. */
    bool switchedOut;

    /** The latency to handle a trap.  Used when scheduling trap
     * squash event.
     */
    Tick trapLatency;

    /** The interrupt fault. */
    Fault interrupt;

    /** The commit PC of each thread.  Refers to the instruction that
     * is currently being processed/committed.
     */
    Addr PC[Impl::MaxThreads];

    /** The commit micro PC of each thread.  Refers to the instruction that
     * is currently being processed/committed.
     */
    Addr microPC[Impl::MaxThreads];

    /** The next PC of each thread. */
    Addr nextPC[Impl::MaxThreads];

    /** The next NPC of each thread. */
    Addr nextNPC[Impl::MaxThreads];

    /** The next micro PC of each thread. */
    Addr nextMicroPC[Impl::MaxThreads];

    /** The sequence number of the youngest valid instruction in the ROB. */
    InstSeqNum youngestSeqNum[Impl::MaxThreads];

    /** Records if there is a trap currently in flight. */
    bool trapInFlight[Impl::MaxThreads];

    /** Records if there were any stores committed this cycle. */
    bool committedStores[Impl::MaxThreads];

    /** Records if commit should check if the ROB is truly empty (see
        commit_impl.hh). */
    bool checkEmptyROB[Impl::MaxThreads];

    /** Pointer to the list of active threads. */
    std::list<ThreadID> *activeThreads;

    /** A struct to hold all information related to static inst blocks. */
    struct StaticInstBlockEntry
    {
        StaticInstBlockEntry() :
            numTypes(0),
            numExits(0),
            numMispredicts(0)
        {
            numInstancesByTakenTypes.resize(TheISA::NumBranchType,
                    static_cast<int>(0));
        }

        /** Times this static block produces a specified exit type during its
         * runtime life.
         * */
        std::vector<int> numInstancesByTakenTypes;

        /** Number of exit types of this static block. Only calculate types by
         * instruction type. Sequential type is excluded since it's a dynamic
         * concept.
         * */
        int numTypes;

        /** Number of exits of this static block */
        int numExits;

        /** Number of mispredicts this static block delivers during its
         * runtime life.
         * */
        int numMispredicts;
    };

    /**
     * A hash_map for holding the information of each static inst
     * block instance.
     * */
//    typedef std::vector<int> StaticInstBlockEntry;
    m5::hash_map<Addr, StaticInstBlockEntry*> staticInstBlockMap;

    struct staticEntryOp
    {
        bool operator() (const std::pair<Addr, StaticInstBlockEntry*> &lhs,
                const std::pair<Addr, StaticInstBlockEntry*> &rhs) const
        {
            int sum1 = std::accumulate((*(lhs.second)).numInstancesByTakenTypes.begin(),
                    (*(lhs.second)).numInstancesByTakenTypes.end(), 0);

            int sum2 = std::accumulate((*(rhs.second)).numInstancesByTakenTypes.begin(),
                    (*(rhs.second)).numInstancesByTakenTypes.end(), 0);

            return (sum1 > sum2);
        }
    };

    /** Stat for the number of committed usefule instructions. */
    //Stats::Formula commitCommittedUsefulInsts;
    /** Stat for the percent of NOP instructions. */
    Stats::Formula commitPercentNop;
    /** Stat for the number of committed NOP instructions. */
    Stats::Scalar commitCommittedNopInsts;
    /** Stat for the total number of committed instructions. */
    Stats::Scalar commitCommittedInsts;
    /** Stat for the total number of committed writes. */
    Stats::Scalar commitCommittedWrites;
    /** Stat for the total number of committed reads. */
    Stats::Scalar commitCommittedReads;
    /** Stat for the total number of committed blocks. */
    Stats::Scalar commitCommittedInstBlocks;
    /** 
     * Stat for the total number of committed blocks with sequential
     * target.
     * */
    Stats::Scalar commitCommittedSeqInstBlocks;
    /** Percent of the blocks with sequential target. */
    Stats::Formula commitSeqInstBlocksFraction;

    /** Stat for the total number of squashed instructions discarded by commit.
     */
    Stats::Scalar commitSquashedInsts;
    /** Stat for the total number of times commit is told to squash.
     * @todo: Actually increment this stat.
     */
    Stats::Scalar commitSquashEvents;
    /** Stat for the total number of times commit has had to stall due to a non-
     * speculative instruction reaching the head of the ROB.
     */
    Stats::Scalar commitNonSpecStalls;
    /** Stat for the total number of branch mispredicts that caused a squash. */
    Stats::Scalar branchMispredicts;
    /** Stat for the total number of exit mispredicts. */
    Stats::Scalar exitMispredicts;
    /** Stat for the total number of type mispredicts, without considering the
     * final result. */
    Stats::Scalar branchTypeOnlyMispredicts;
    /** Stat for breakdown of the mispredict rate of branch type,
     * without considering the final result.*/
    Stats::Formula branchTypeOnlyMispredictRateSeq;
    Stats::Formula branchTypeOnlyMispredictRateBranch;
    Stats::Formula branchTypeOnlyMispredictRateCall;
    Stats::Formula branchTypeOnlyMispredictRateReturn;

    /** Breakdown for hyperblocks by dynamic branch type. */
    Stats::Vector dynamicBlockByBranchType;
    /** Breakdown for hyperblock mispredicts by dynamic branch type. */
    Stats::Vector branchTypeOnlyMispredictsBreakDown;

    /** Stat for recording the mispredicts from branch target buffers, without
     * considering exit and/or type predictions. */
    Stats::Vector branchTargetBuffersMispredicts;
    /** Stat for the total number of exit mispredicts combined with type
     * mispredicts, without considering the final result. */
    Stats::Scalar exitAndTypeOnlyMispredicts;
    /** Stat for the total number of exit and branch target mispredicts. */
    Stats::Scalar exitAndBranchMispredicts;
    /** Stat for the number of mispredicted branches. */
    Stats::Vector branchTypeMispredicts;
    /** 
     * Stat for the number of exit misprediction combined with branch
     * type misprediction.
     * */
    Stats::Scalar exitAndTypeMispredicts;
    /**
     * Stat for the number of mispredicted branch type for sequential
     * branch target.
     * */
    Stats::Vector seqBranchTypeMispredicts;
    /** Number of correct prediction. */
    Stats::Scalar correctPredictions;
    /** Percent of correct predictions of all committed inst blocks. */
    Stats::Formula branchPredRate;
    /** Distribution of the number of committed useful insts each cycle. */
    Stats::Distribution numCommittedDist;

    /** Average percentage of the most taken branch type in a block. */
    Stats::Scalar branchTypeTendencyInBlock;

    /** Top 100 instances' taken branch type percentage. */
    Stats::Vector branchTypeTop100SeqPercent;
    Stats::Vector branchTypeTop100BranchPercent;
    Stats::Vector branchTypeTop100CallPercent;
    Stats::Vector branchTypeTop100RetPercent;

    /** Classes of inst blocks with top 100 instances, categorised as follows:
     * 
     *  Static type         
     *  1 type       100% seq    100% branch   100% call   100% return   both seq/other    rest
     *  2 types      ...
     *  3 types      ...
     *
     * */
    Stats::Vector2d branchTypeTopNClasses;

    /**
     * Mispredicts for each type of hyperblocks. Hyperblocks are classified
     * by their dynamically produced exit types. There are 6 classes of
     * hyperblocks: 100% dominated by seq, 100% dominated by branch, 100%
     * dominated by call, 100% dominated by return, having both seq and other
     * types, and the other cases. 
     * */
    Stats::Vector branchMispredictsClassified;

    Stats::Vector numInstancesClassified;

    Stats::Formula mispredictRateAllSeq;
    Stats::Formula mispredictRateAllBranch;
    Stats::Formula mispredictRateAllCall;
    Stats::Formula mispredictRateAllReturn;
    Stats::Formula mispredictRateBothSeqAndOthers;
    Stats::Formula mispredictRateOthers;

    /** Distribution of exit types for each static hyperblock, indirect types
     * are included. */
    Stats::Distribution branchTypeCompleteClasses;

    /** Categorise static blocks by number of exit types. 0: number of static
     * blocks with only one type of exits, 1: number of static blocks with two
     * types of exits, 2: number of static blocks with three types of exits.
     * Note that this stats will not include sequential target, since it's a
     * dynamic concept.
     * */
    Stats::Vector staticBlockByNumTypes;

    /** Categorise static blocks by number of exits. Maximum 8 is allowed.
     * */
    Stats::Vector staticBlockByNumExits;

    /** Average percentage of branch type in a block. 0: seq, 1:
     * branch, 2: call, 3: ret. */
    Stats::Vector branchTypePercentageInBlock;
    /** Overall percentage of branch type across all dynamic block
     * instances. 0:seq, 1:branch, 2:call, 3:ret. */
    Stats::Vector branchTypePercentageOverall;

    /** Distribution of static instruction blocks with different most
     * taken branch types.*/
    Stats::Distribution branchTypeMaxDist;

    /** Average percentage of most taken branch type of blocks with
     * different most taken types. */
    Stats::Vector branchTypeTendencyType;

    /** Total number of instructions committed. */
    Stats::Vector statComInstBlock;

    /** Number of cycles where the commit bandwidth limit is reached. */
    Stats::Scalar commitEligibleSamples;
    /** Number of instructions not committed due to bandwidth limits. */
    Stats::Vector commitEligible;

    /** Stats for the exit id of each committed block. */
    Stats::Distribution commitExitID;

    /** Stats for the exit id of blocks with different exit. */
    Stats::VectorDistribution commitExitIDOfDiffNumExitBlocks;
};

#endif // __CPU_EDGE_COMMIT_HH__
